<?
$USB_OUT_FILE = '/var/log/usb-backup.log';
$USB_IN_FILE = '../services/rdiffbackup/in';
$USB_LOCK_FILE = '/var/run/uggla_rdiff_usb_backup.lock';
$SFTP_OUT_FILE = '/var/log/sftp-backup.log';
$SFTP_IN_FILE = '../services/rdiffbackup/in';
$SFTP_LOCK_FILE = '/var/run/uggla_rdiff_sftp__backup.lock';


function create_timemap( $cron_file )
{
	$cron_times = array();
	if( file_exists( $cron_file ) ) {
		$fbuf = @file( $cron_file );
		foreach( $fbuf AS $line ) {
			$crons = explode(" ",$line);
			$hours = explode(",", $crons[1]);
			$day = $crons[4];
			foreach( $hours AS $hour )
				$cron_times[] = $day.$hour;
		}
	}

	$days = array('måndag'=>'mon','tisdag'=>'tue','onsdag'=>'wed','torsdag'=>'thu','fredag'=>'fri','lördag'=>'sat','söndag'=>'sun');
	$hours = array('00','01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23');
	echo '
<script type="text/javascript">
<!--
var mousestat=false;
var mousefocus=false;

function mousedw() {
	mousestat=true;
}

function mouseup() {
	mousestat=false;
	mousefocus=false;
}
document.onmousedown=mousedw;
document.onmouseup=mouseup;

function changechecked(name) {
	if( document.getElementById(name).checked ) {
		document.getElementById(name).checked=false;
	}
	else {
		document.getElementById(name).checked=true;
	}
}

function checkmousedown(name) {
	if( mousestat ) {
		changechecked(name);
	}
}

function focuson(name) {
	mousefocus = name;
	changechecked(name);
}

function focusoff(name) {
	if( mousefocus == name ) {
		changechecked(name);
	}
	mousefocus=false;
}

var days=[';
$str = "";
foreach( $days AS $day )
	$str .= ",'$day'";
echo substr($str, 1);
echo '];
var hours=[';
$str = "";
foreach( $hours AS $hour )
	$str .= ",'$hour'";
echo substr($str, 1);
echo '];
function backup_time_never() {
	for( day in days ) {
		for( hour in hours ) {
			document.getElementById( days[day]+hours[hour] ).checked=false;
		}
	}		
}

function backup_time_every() {
	for( day in days ) {
		for( hour in hours ) {
			document.getElementById( days[day]+hours[hour] ).checked=true;
		}
	}		
}

function backup_time_everysec() {
	for( day in days ) {
		for( hour in hours ) {
			if( hour%2 == 0  ) {
				document.getElementById( days[day]+hours[hour] ).checked=false;
			}
			else {
				document.getElementById( days[day]+hours[hour] ).checked=true;
			}
		}
	}		
}

function backup_time_one() {
	backup_time_never();
	for( day in days ) {
		document.getElementById( days[day]+"01" ).checked=true;
	}
}

function backup_time_worktime() {
	var days = ["mon","tue","wed","thu","fri"];
	var hours = ["08","09","10","11","12","13","14","15","16","17","18"];
	backup_time_never();
	for( day in days ) {
		for( hour in hours ) {
			document.getElementById( days[day]+hours[hour] ).checked=true;
		}
	}		
}
-->
</script>
	';
	echo '<div style="font-size:80%;" '.help('backup_auto').'>välj: ';
	echo '<a style="color:#00a" href="javascript:backup_time_one()">varje dag</a>,&nbsp;&nbsp;';
	echo '<a style="color:#00a" href="javascript:backup_time_worktime()">arbetstid</a>,&nbsp;&nbsp;';
	echo '<a style="color:#00a" href="javascript:backup_time_every()">varje timme</a>,&nbsp;&nbsp;';
	echo '<a style="color:#00a" href="javascript:backup_time_everysec()">varannan timme</a>,&nbsp;&nbsp;';
	echo '<a style="color:#00a" href="javascript:backup_time_never()">aldrig</a>';
	echo '</div>';
	echo '<table '.help('backup_auto').'>';
	echo '<tr><td>&nbsp;</td>';
	foreach( $hours AS $i )
		echo "<td>$i</td>";
	echo '</tr>';
	foreach( $days AS $dayname => $dayshort ) {
		echo "<tr><td>$dayname</td>";
		foreach( $hours AS $hour ) {
			$name = $dayshort.$hour;
			if( in_array( $name, $cron_times ) )
				echo '<td><input checked style="width:20px;height:20px;margin:0em" type="checkbox" id="'.$name.'" name="'.$name.'"';
			else
				echo '<td><input style="width:20px;height:20px;margin:0em" type="checkbox" id="'.$name.'" name="'.$name.'"';
			echo '       onFocus="javascript:focuson(\''.$dayshort.$hour.'\');" onMouseOver="javascript:checkmousedown(\''.$dayshort.$hour.'\');" onMouseUp="javascript:focusoff(\''.$dayshort.$hour.'\');"></td>';
		}
		echo '</tr>';
	}
	echo '</table>';
}


function showStartUSB()
{
/*
BACKUP
läser sträng från cron.d/backup
*/
	global $BASE_DIR;
	require($BASE_DIR."inc/ajax.php");
	require($BASE_DIR."inc/rwINIfile.php");

	$filebuf = readINIfile('/etc/rdiff-backup-usb', '#');

        $system=false;
        $mail=false;
        $groupware=false;
	if( isset($filebuf['data']['include_system']) AND ($filebuf['data']['include_system'] == 'true') )
		$system = true;
	if( isset($filebuf['data']['include_mail']) AND ($filebuf['data']['include_mail'] == 'true') )
		$mail = true;
	if( isset($filebuf['data']['include_groupware']) AND ($filebuf['data']['include_groupware'] == 'true') )
		$groupware = true;
	
	if( isset($filebuf['data']['remove_older_than']) )
		$remove_older_than = $filebuf['data']['remove_older_than'];
	else
		$remove_older_than = "NEVER";

	if( is_array($filebuf['included_files']) )
		$checked = $filebuf['included_files'];
	else
		$checked = array();

	echo '<div id="usbstat_div"><img src="/images/loading.gif">&nbsp;Hämtar information om USB</div><br><br>';
	echo '
<SCRIPT LANGUAGE="JavaScript" type="text/javascript">
<!-- Hide script from old browsers
function ajaxhandler( xmlHttp, id ) {
	var arr = xmlHttp.responseText.split("^");
	var str = "";
	var redo = false;

	//trim
	arr[0] = arr[0].replace(/^\s+/, "");
	arr[0] = arr[0].replace(/\s+$/, "");

	if( arr[0] == "creating" )
		str = "<b>Skapar backupenhet</b><br><img src=\"/images/loading.gif\">&nbsp;detta tar ett tag..";
	else if( arr[0] == 0 )
		str = "<b>Ingen usb-enhet är ansluten</b><br>Anslut en USB-hårddisk för att utföra USB-backup.";
	else if( arr[0] > 0 ) {
		if( arr[0] > 1 )
			str = "<b style=\"color: #f00\">Fler än den visade externa hårddisken är anslutna, dock finns ännu enbart stöd för att visa en enhet.</b><br><br>";

		var name = arr[2] + " " + arr[3];
		if( arr[1] == "false" )
			str = str + "<b>Den anslutna enheten behöver aktiveras som backupenhet.</b><br>Vill du aktivera " + name + " som en backupenhet?<br>All tidigare information på " + name + " kommer att försvinna.<br><input type=\"submit\" value=\"Aktivera enhet\" name=\"dobackupdev\" class=\"buttonlong\">";
		else {
			var space_total = arr[4];
			var space_free = arr[5];
			str = str + "<b>" + name + " är redo för backup</b><br>" + space_free + " används av totalt " + space_total;
			redo = true;
		}
	}
	document.getElementById("usbstat_div").innerHTML = str;
	if( redo ) {
		document.getElementsByName("b_usbnow")[0].disabled = false;
	}
	else {
		document.getElementsByName("b_usbnow")[0].disabled = true;
	}
}
function statrequest() {
	ajax_send( "ajax.php", "jsfunc", ajaxhandler, "usbstat", null);
	setTimeout("statrequest()", 1000);
}
statrequest();
// End hiding script from old browsers -->
</SCRIPT>
	';


	echo '<div '.help('backup_filetree').'><table style="border: solid 1px #ccc">';
	echo '<tr><td class="tbhead">Vilka kataloger ska ingå i backupen?</td></tr>';
	echo '<tr><td>';
	treelist(DIRTREE, array('/home/', '/var/shares/'), 'backuptree', $checked);
	echo '</table></div><br>';

	echo '<table>';
	echo '<tr><td class="tbhead" colspan=2>Vad mer ska ingå i backupen?</td></tr>';
	echo '<tr><td><input type="checkbox" name="system" '.($system?'checked':'').'> systeminställningar</td><td>&nbsp;(användarregister, tjänstinställningar)</td></tr>';
	echo '<tr><td><input type="checkbox" name="mail" '.($mail?'checked':'').'> användares mail</td><td>&nbsp;</td></tr>';
	echo '<tr><td><input type="checkbox" name="groupware" '.($groupware?'checked':'').'> groupwaredata utöver mail</td><td>&nbsp;(kalender, adressbok)</td></tr>';
	echo '</table><br>';

	echo '<div '.help('backup_removetime').'><table>';
	echo '<tr><td class="tbhead">Hur lång tid tillbaka i tiden ska det gå att återställa från backupen?</td></tr>';
	echo '<tr><td>Radera backuptidpunkter äldre än&nbsp;&nbsp;';
	echo  '<select name="removetime">';
	foreach( array("1D" => "1 dag", "1W" => "1 vecka", "1M" => "1 månad", "2M" => "2 månader", "6M" => "6 månader", "1Y" => "1 år", "NEVER" => "radera aldrig") AS $key => $value ) {
		if( $key == $remove_older_than )
			echo "<option value='$key' selected>$value</option>";
		else
			echo "<option value='$key'>$value</option>";
	}
	echo  '</select>';
	echo '</td></tr>';
	echo '</table></div><br>';

	echo '<table>';
	echo '<tr><td class="tbhead" '.help('backup_auto').'>Vilka tider ska automatisk backup genomföras? (lämna tom för aldrig)</td></tr>';
	echo '<tr><td>';
	create_timemap('/etc/cron.d/rdiff_backup');
	echo '</td></tr>';
	echo '</table><br>';

	echo '<table>';
	echo '<tr><td class="tbhead" '.help('usb_backup_start').'>Utför backup nu på en gång</td></tr>';
	echo '<tr><td '.help('usb_backup_start').'><input type="submit" class="button" name="b_usbnow" value="Utför nu" disabled></td></tr>';
	echo '</table><br>';
}


function showStartSFTP()
{
	global $BASE_DIR;
	require($BASE_DIR."inc/ajax.php");
	require($BASE_DIR."inc/rwINIfile.php");
	
	//unset($_SESSION['sftp']);

	$filebuf = readINIfile('/etc/rdiff-backup-sftp', '#');
	$user = $filebuf['data']['user'];
	$passwd = $filebuf['data']['passwd'];

	if( $filebuf['data']['include_system'] == 'true' )
		$system = true;
	if( $filebuf['data']['include_mail'] == 'true' )
		$mail = true;
	if( $filebuf['data']['include_groupware'] == 'true' )
		$groupware = true;

	if( is_array($filebuf['included_files']) )
		$checked = $filebuf['included_files'];
	else
		$checked = array();

	echo '<table>';
	echo '<tr><td class="tbhead" colspan=2>Kontouppgifter</td></tr>';
	echo '<tr><td>användarnnamn:&nbsp;</td><td><input type="text" name="user" value="'.$user.'"></td></tr>';
	echo '<tr><td>lösenord:&nbsp;</td><td><input type="password" name="passwd" value="'.$passwd.'"></td></tr>';
	echo '</table><br>';

	echo '<table style="border: solid 1px #ccc">';
	echo '<tr><td class="tbhead">Vilka kataloger ska ingå i backupen?</td></tr>';
	echo '<tr><td>';
	treelist(DIRTREE, array('/home/', '/var/shares/'), 'backuptree', $checked);
	echo '</table><br>';

	echo '<table>';
	echo '<tr><td class="tbhead" colspan=2>Vad mer ska ingå i backupen?</td></tr>';
	echo '<tr><td><input type="checkbox" name="system" '.($system?'checked':'').'> systeminställningar</td><td>&nbsp;(användarregister, tjänstinställningar)</td></tr>';
	echo '<tr><td><input type="checkbox" name="mail" '.($mail?'checked':'').'> användares mail</td><td>&nbsp;</td></tr>';
	echo '<tr><td><input type="checkbox" name="groupware" '.($groupware?'checked':'').'> groupwaredata utöver mail</td><td>&nbsp;(kalender, adressbok)</td></tr>';
	echo '</table><br>';

	echo '<table>';
	echo '<tr><td class="tbhead">Vilka tider ska automatisk backup genomföras? (lämna tom för aldrig)</td></tr>';
	echo '<tr><td>';
	create_timemap('/etc/cron.d/sftp_rdiff_backup' );
	echo '</td></tr>';
	echo '</table><br>';

	echo '<table>';
	echo '<tr><td class="tbhead">Utför backup nu på en gång</td></tr>';
	echo '<tr><td><input type="submit" class="button" name="b_sftpnow" value="Utför nu"></td></tr>';
	echo '</table><br>';
}


function showUSBrestore()
{
	require('../inc/ajax.php');

	exec('/usr/share/uggla/services/rdiffbackup/usb_rdiff_wwwadmin device', $device);
	if( $device[0] == "not connected" ) {
		echo '<a href="main.php?s=rdiffbackup&t=usbrestore" style="color: #00f; font-size: 70%">Uppdatera status</a><br>';
		echo "<b>Ingen USB-enhet med backup är ansluten<b><br><br>";
	}
	else {
		$type = explode('^', $device[0]);
		$mpoint = $type[1];
		$vendor = $type[2];
		$model = $type[3];
		$name = "$vendor $model";

		// Kontroll om backup skett tidigare
		if( ! is_dir("$mpoint/bkp") ) {
			echo '<b>Ingen tidigare backuptidpunkt hittades på USB-hårddisken</b>';
			echo '<p>Kan ej återställa från backupenheten då den inte innehåller någon backupdata.</p>';
			return;
		}

		// Kontroll om tidigare backup lyckats
		exec('/usr/bin/rdiff-backup --parsable-output -l '.$mpoint.'/bkp 2> /dev/null', $incs, $ret);
		if( $ret != 0 ) {
			echo '<b>Tidigare backup verkar ha misslyckas</b>';
			echo '<p>Backupdatan måste återställas till tidpunkt före avbruten backup.<br>Kör en ny backuprunda eller klicka på "Återställ backup" för att återställa backupdatan.</p>';
			echo '<input type="submit" class="buttonlong" name="b_usbrevert" value="Återställ backup">';
			return;
		}
		
		if( isset($_GET['rtime']) && intval($_GET['rtime'])>0 )
			$rtime = intval($_GET['rtime']);
		else
			$rtime = 'now';

		if( isset($_GET['directory']) )
			$directory = $_GET['directory'];
		else
			$directory = "";

		if( isset($_GET['restoretype']) ) {
			if( $_GET['restoretype'] == 'jump' )
				$restoretype = 'jump';
			else
				$restoretype = 'get';
		}
		else
			$restoretype = "";


		echo '<a href="main.php?s=rdiffbackup&t=usbrestore" style="color: #00f; font-size: 70%">Uppdatera status</a><br>';
		echo "'$name' är ansluten<br><br>";

                echo "<b>Tidpunkt att återställa från:</b><br>";
		echo '<select name="rtime" onChange="javascript:document.getElementById(\'b_rtime\').click();">';
		arsort( $incs );
		foreach( $incs AS $inc ) {
			$time = explode(' ', $inc);
			$time = $time[0];
			if( $time == $rtime )
				echo '<option value="'.$time.'" selected>'.date("Y-m-d H:i", $time);
			else
				echo '<option value="'.$time.'">'.date("Y-m-d H:i", $time);
		}
		echo "</select>";
		echo '<input type="submit" value="ladda om" name="b_rtime" id="b_rtime" class="button"><br><br>';

		echo '<div '.help('restore_type').'><table>';
		echo '<tr><td class="tbhead">Hur vill du återställa data?</td></tr>';
		echo '<tr><td><input name="restoretype" value="get" type="radio" '.(($restoretype == 'get')?'checked':'').' onClick="javascript:document.getElementById( \'div_jump\' ).style.display = \'none\';document.getElementById( \'div_get\' ).style.display = \'\'">Hämta enskilda filer och kataloger</td></tr>';
		echo '<tr><td><input name="restoretype" value="jump" type="radio" '.(($restoretype == 'jump')?'checked':'').' onClick="javascript:document.getElementById( \'div_get\' ).style.display = \'none\';document.getElementById( \'div_jump\' ).style.display = \'\'">Hoppa tillbaka till en tidigare tidpunkt</td></tr>';
		echo '</table></div><br>';

	// Hämta filer eller kataloger
		echo '<div id="div_get" style="padding:0.5em;border: 1px solid #999; display:none">';

		echo "<b>Hemkatalog filerna ska läggas under:</b><br>";
		echo '<select name="directory">';
		$dirs = scandir('/home/');
		foreach( $dirs AS $dir ) {
			if( $dir != '.' && $dir != '..' ) {
				if( $directory == $dir )
					echo '<option value="'.$dir.'" selected>'.$dir.'\\restore\\';
				else
					echo '<option value="'.$dir.'">'.$dir.'\\restore\\';
			}
		}
		echo '</select>';
		echo '<br><br>';

		echo "<b>Välj de filer och kataloger du vill hämta:</b>";
		$files = array();
		if( sizeof($incs) > 0 )
			exec('/usr/bin/rdiff-backup --list-at-time '.$rtime.' '.$mpoint.'/bkp/', $files);
                $filtered_files = preg_grep ( "#^(home$|home/|var/shares$|var/shares/)#" , $files);
		treelist(ARRAYTREE, $filtered_files, 'restoretree');

		echo '<br>';
		echo '<input type="submit" value="Utför" name="b_rstart" class="button">';

		echo '</div>';

	// Hoppa tillbaka till tidigare punkt
		echo '<div id="div_jump" style="padding:0.5em;border: 1px solid #999;display:none">';

		$homes = (count(preg_grep('#^home/#', $files)) > 0 );
		$shares = (count(preg_grep('#^var/shares#', $files)) > 0 );
		$system = (count(preg_grep('#^etc/#', $files)) > 0 );
		$mail = (count(preg_grep('#^var/spool/cyrus/#', $files)) > 0 );
		$groupware = (count(preg_grep('#^var/backups/mysqldump.sql.gz$#', $files)) > 0 );

		echo "<b>Vad ska återställas:</b><br>";
		echo '<input type="checkbox" name="homes" '.($homes?'':'disabled').'>Hemkataloger<br>';
		echo '<input type="checkbox" name="shares" '.($shares?'':'disabled').'>Fildelningar<br>';
		echo '<input type="checkbox" name="system" '.($system?'':'disabled').'>Systeminställningar (användardatabas, tjänstinställningar)<br>';
		echo '<input type="checkbox" name="mail" '.($mail?'':'disabled').'>Användares mail<br>';
		echo '<input type="checkbox" name="groupware" '.($groupware?'':'disabled').'>Groupwaredata utöver mail (kalender, adressbok)<br><br>';
		echo '<input type="submit" value="Utför" name="b_jstart" class="button" '.confirm('restore_jump').'><br>';

		echo '</div><br>';

		
		if( isset($_GET['restoretype']) AND ($_GET['restoretype'] != '') ) {
			echo '
<SCRIPT LANGUAGE="JavaScript" type="text/javascript">
<!-- Hide script from old browsers
			';
			if( $_GET['restoretype'] == 'get' )
				echo 'document.getElementById( \'div_get\' ).style.display = \'\';';
			else if( $_GET['restoretype'] == 'jump' )
				echo 'document.getElementById( \'div_jump\' ).style.display = \'\';';
			echo '
// End hiding script from old browsers -->
</SCRIPT>
			';
		}
	}
}

function showAlreadyUSB()
{
        echo "En backupkörning pågår, vad vill du göra?<br><br>\n";
	echo '<input type="hidden" name="t" value="usb">';
        echo '<input class="buttonlong" name="showusb" type="submit" value="Visa pågående">';
}


function showAlreadySFTP()
{
        echo "En backupkörning pågår, vad vill du göra?<br><br>\n";
	echo '<input type="hidden" name="t" value="sftp">';
        echo '<input class="buttonlong" name="showsftp" type="submit" value="Visa pågående">';
}

function RdiffRestore( $outfile )
{
	$arr = @file( $outfile );
	$done = 0;
	$error = 0;

	$str = "Påbörjar hämtning...<br>\n";
        if( is_array($arr) ) {
		foreach( $arr AS $line ) {
			if( preg_match('[^DO:\ ]', $line) ) {
				$arr = explode(' ', $line);
				unset($arr[0]);
				$file = implode(' ', $arr);
				if( strlen($file) > 80 )
					$file = substr($file, 0, 78).'..';
                                $str = "Återställer:<br><i>".$file."</i><br>\n";
			}
			else if( preg_match('[^Done!$]', $line) ) {
				$str = "Klar<br>\n";
				$done = 1;
			}
			else if( preg_match('[^ERROR$]', $line) ) {
				$str = "Fel har skett<br>\n";
				$error = 1;
				$done = 1;
			}
		}

	}
	echo "<b>Process:</b><br>\n $str";
        if ($done == 1) {
		if( !$error )
                	echo "<br>\nHämtningen är klar.<br>";
		else
			echo "<br>\nHämtningen misslyckades.<br>";
        }
}


function showRdiffRunning($infile, $outfile)
{
        $arr = @file( $outfile );

	$search  = array( '#^(home/)#', '#^(var/shares/)#' );
	$replace = array( 'Hemkataloger/', 'Fildelningar/' );
	$done = 0;
	$error = 0;
	
        $str = "Startar upp....<br>\n";
        if( is_array($arr) ) {
                foreach( $arr AS $line ) {
			if( preg_match('[^(RESTORE|REVERT)$]', $line) ) {
				$str = RdiffRestore( $outfile );
				return;
			}
			else if( preg_match('[^Connecting...$]', $line) ) {
				$str = "Ansluter...<br>";
			}
			else if( preg_match('[^Connected$]', $line) ) {
				$str = "Ansluten, påbörjar backup...<br>";
			}
                        else if( preg_match('[^Processing changed file ]', $line) ) {
				$arr = explode(' ', $line);
				unset($arr[0]);
				unset($arr[1]);
				unset($arr[2]);
				$file = implode(' ', $arr);
				if( strlen($file) > 70 )
					$file = rtrim(substr($file, 0, 68)).'..';
				$filealias = preg_replace($search, $replace, $file);
                                $str = "Synkroniserar den förändrade filen:<br><i>".$filealias."</i><br>\n";
			}
			else if( preg_match('[^Regressing file ]', $line) ) {
				$arr = explode(' ', $line);
				unset($arr[0]);
				unset($arr[1]);
				$file = implode(' ', $arr);
				if( strlen($file) > 70 )
					$file = rtrim(substr($file, 0, 68)).'..';
				$filealias = preg_replace($search, $replace, $file);
				$str = "Då tidigare backup-körning avbröts måste backupdatan återställas.<br>";
				$str .= "Återställer filen:<br><i>".$filealias."</i><br>\n";
			}
                        else if( preg_match('[^Writing mirror_metadata diff$]', $line) )
				$str = "Sparar backupinformation<br>\n";
                        else if( preg_match('[^Traceback \(most recent call last\)]', $line) ) {	
				$done = 1;
				$error = 1;
				$str = "FEL: Ett okänt fel har skett<br>\n";
			}
			else if( preg_match('[\[Errno 5\] Input/output error]', $line) ) {
				$done = 1;
				$error = 1;
				$str = "FEL: Tappade kontakten med backup-enheten, sitter kabeln i ordentligt?<br>\n";
			}
                        else if( preg_match('[^Cleaning up$]', $line) ) {
                                $done = 1;
                                $str = "Klar.<br>\n";
			}
		}
	}

	if( isset($_GET['t']) )
		echo '<input type="hidden" name="t" value="'.htmlentities($_GET['t']).'">';
	else
		echo '<input type="hidden" name="t" value="usb">';

	echo "<b>Process:</b><br>\n $str";
        if ($done == 1) {
		if( !$error )
                	echo "<br>\nBackupkörningen är klar.";
		else
			echo "<br>\nBackupkörningen misslyckades.<br>";
        }
        else {
                echo "<br>\n".'<input class="button" type="submit" name="stopbackup" value="Stoppa">';
        }
}


////////////////////////////////////////
////////////////////////////////////////

$tabsstart = array(
          array('usb', 'USB - backup'),
          //array('sftp', 'Fjärr - backup'),
	  array('usbrestore', 'Återställ från USB') );
	  //array('sftprestore', 'Återställ från fjärr') );

if( isset($_GET['t']) ){
	$tabsrunning = array(
                array( $_GET['t'] , 'Pågående backupkörning') );
}
else {
	$tabsrunning = array(
        	array( 'usb' , 'Pågående backupkörning') );
}
	
	if( ! isset($_GET['part']) ) {
                //Is rdiff_backup_usb running?
		if( is_file($USB_LOCK_FILE) ) {
			html_start( $tabsrunning, 5);
			showAlreadyUSB();
			html_end();
			exit;
		}
                //Is rdiff_backup_sftp running?
		if( is_file($SFTP_LOCK_FILE) ) {
			html_start( $tabsrunning, 5);
			showAlreadySFTP();
			html_end();
			exit;
		}
	}

        $t='';
        if( isset($_GET['t']) )
            $t=$_GET['t'];
        
	switch ( $t ) {
	default:
                $part = '';
                if( isset($_GET['part']) )
                    $part=$_GET['part'];

		switch ( $part ) {
		default:
			html_start( $tabsstart );
			if( $t=='sftp' ) {
				showStartSFTP();
				html_end(1,1,1);
			}
			else {
				showStartUSB();
				html_end(1,1,1);
			}
			break;
		case 'usbrunning':
			html_start( $tabsrunning, 5);
			showRdiffRunning($USB_IN_FILE, $USB_OUT_FILE);
			html_end();
			break;
		case 'sftprunning':
			html_start( $tabsrunning, 5);
			showRdiffRunning($SFTP_IN_FILE, $SFTP_OUT_FILE);
			html_end();
			break;
		case 'stopped':
			html_start( $tabsrunning, 5);
			showStopped();
			html_end(0,0,0, 'rdiffbackup', $_GET['t']);
			break;
		}
		break;
	case 'usbrestore':
		if( isset($_GET['part']) && $_GET['part']=='usbrunning' ) {
			html_start( $tabsrunning);
			showRdiffRunning($USB_IN_FILE, $USB_OUT_FILE);
			html_end();
		}
		else {
			html_start( $tabsstart );
			showUSBrestore();
			html_end();
		}
		break;	
	case 'sftprestore':
		if( isset($_GET['part']) && $_GET['part']=='usbrunning' ) {
			html_start( $tabsrunning, 5);
			showRdiffRunning($SFTP_IN_FILE, $SFTP_OUT_FILE);
			html_end();
		}
		else {
			html_start( $tabsstart );
			showUSBrestore();
			html_end();
		}
		break;
	}

?>

